package com.atguigu.gmall.common.minio.service.impl;

import com.atguigu.gmall.common.minio.config.MinioProperties;
import com.atguigu.gmall.common.minio.service.OSSService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/9/7 2:14
 */
@Service
public class OSSServiceImpl implements OSSService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties minioProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        String path=null;
        try {
            //检查桶是否存在
            boolean b = minioClient.bucketExists(minioProperties.getBucket());
            if (b) {
                //存在
                System.out.println("已经存在桶");
            } else {
                //不存在就创建
                minioClient.makeBucket(minioProperties.getBucket());

            }
            //使用上传文件到gmall桶中
            //String bucketName, 桶名
            // String objectName, 文件名
            // InputStream stream, 文件流
            // PutObjectOptions options 参数设置
            InputStream fileInputStream = file.getInputStream();
            String name = UUID.randomUUID().toString().replace("-","").substring(4)+file.getOriginalFilename();
            PutObjectOptions putObjectOptions = new PutObjectOptions(fileInputStream.available(), -1);
            putObjectOptions.setContentType("image/jpeg");
            minioClient.putObject(minioProperties.getBucket(), name, fileInputStream, putObjectOptions);
            path=minioProperties.getEndpoint()+"/"+minioProperties.getBucket()+"/"+name;


        } catch (Exception e) {
            System.err.println("Error occurred: " + e);
        }

        return path;

    }
}
